<?php

defined( 'IN_DICE' ) or die( 'Access Error!' );

include_once( DIR_MDL . 'platform/platform.php' );
include_once( DIR_MDL . 'platform/class.sdo.php' );

class sdo implements platform {
	
	/**
	 * @var XNapp
	 */
	public $op;
	public $pfid;
	public $apiid;
	public $apikey;
	public $apisecret;
	public $apiurl;
	public $payurl = 'http://oppay.sdo.com/pay/'; //盛大支付平台地址
	public $pfkey = '';
	public $apilogin = '';
	
	public function __construct() {
		$this->pfid = all::$cfg['sdo_pfid'];
		$this->apiid = all::$cfg['sdo_apiid'];
		$this->apikey = all::$cfg['sdo_apikey'];
		$this->apisecret = all::$cfg['sdo_apisecret'];
		$this->apiurl = all::$cfg['sdo_apiurl'];
		$this->apilogin = all::$cfg['platform'][$this->pfid]['url'];

		$this->getpfkey();
	}

	public function getpfkey() {
		if( isset( $_GET['sdo_sig_session_key']) ) {
			$this->pfkey = $_GET['sdo_sig_session_key'];
			setcookie( 'pfkey', $this->pfkey );
		} else if( isset( $_COOKIE['pfkey'] ) ) {
			$this->pfkey = $_COOKIE['pfkey'];
		}
	}
	
	/**
	 * 获取当前登录用户的平台ID.字符串型,没有获取到则为空字符串
	 */
	public function getUserId() {
		$ret = $this->call( 'Users.getLoggedInUser', array());
	    return isset( $ret['uid'] ) && strlen( $ret['uid'] ) ? $ret['uid'] : '';
	}
	public function getUserInfo( $uid ) {
		$ret = $this->call( 'users.getinfo', array('uids' => $uid));
		model::logs()->debug( $ret, 'getuser.txt' );
		return ( !isset( $ret['id'] ) || ( strcmp($uid, $ret['id']) !== 0 ) ) ? array() : array( //错误则返回空数组,否则严格返回以下格式
																	'puid' => $ret['id'],
																	'uname' => strlen( $ret['name'] ) ? $ret['name'] : $ret['id'],
																	'headurl' => $ret['headurl'],
																	'sex' => $ret['sex'] === '男' ? 1 : 0,
																	'psuid' => '',
																	'upage' => 'http://t.sdo.com/home/'.$uid,
																	'usid' => 0, //用户的子ID,用于同城或者本站
																	'pfid' => all::$cfg['sdo_pfid'],
																	);
	}
	public function getAllFriends(){
		$ret = $this->call( 'friends.getFriends', array());
		return is_array($ret) ? $ret : array();
	}
	public function getAppFriends(){ //获得应用方好友
		$ret = $this->call( 'friends.getAppFriends', array());
		$aF = array();
		if(is_array( $ret ) ) {
			foreach( $ret as $k => $v ) {
				isset($v['id']) && $aF[] = $v['id'];
			}
		}
		return $aF;
	}
	
	/**
	 * 应用授权，用户是否添加此应用或已登录
	 */
	public function isAdded() {
		$ret = $this->call( 'Users.isAppUser', array());
		return isset($ret['result']) && $ret['result'] ? true : false;
	}
	public function getSiteInfo() {
		
	}
	public function sendNotice() {
		
	}
	/**
	 * 发Feed
	 * @param $aFields : template_id = 1; body_data = array('name'=>'zhou', 'visitor'=>'jian'); 分别为注册的模板号和模板值
	 * @param unknown_type $aFields
	 */
	public function sendFeed( $aFields ) {
		$ret = $this->call( 'Feed.publishTemplatizedAction', array('template_id' => $aFields['template_id'], 'body_data' => json_encode( $aFields['body_data'])));

		return isset($ret['result']) && $ret['result'] ? true : false;
	}
	public function setProfile() {
		
	}
	public function setKey( $key ) {
		$this->op->session_key = $key;
	}
	public function hasPermission(){
		$ret = $this->call( 'Users.hasAppPermission', array());

		return $ret ? true : false;
	}
	public function sendInvite( $puid, $uids ) {
		$ids = '';
		count($uids) && $uids = array_slice( $uids, 0, 10);
		count($uids) && $ids = implode( ',', $uids );
		$ret = $this->call( 'invitations.send', array());
		return isset( $ret['result'] ) && $ret['result'] == 1 ? true : false;
	}
	public function getpayurl() {
		return all::$aOut['baseurl'] . '?m=game&a=pay&p=sdo';
	}
	public function genpayurl( $aO ) { //生成某笔订单的平台方的跳转url
		$param = array( //必须参数
			'session_key' => $this->pfkey, //required string	session key
			'order_id' => $aO['apid'], //required int	订单ID
			'order_price' => $aO['pamt'], //required int	订单总金额
			'order_msg' => $aO['pname'], //required string	订单信息，用于显示（UTF-8编码）
			'app_id' => $this->apiid, //required int	应用ID
			'app_key' => $this->apikey, //required string	应用 key
			'uid' => $aO['puid'], //required int	用户数字ID
			'time' => time(), //required int	当前的Unix时间戳
			//'sign' => '', //required string	签名
		);
		
		$paramOption = array( //可选参数
			'oppay_enviroment' => all::$cfg['testapp'] == 1 ? 'sandbox' : '', //optional string	支付环境，sandbox为测试环境，其他为正式环境
			'order_callback_url' => $aO['notifyurl'], //optional string	支付成功或失败回调地址(默认取 盛大点卷接入设置 ->点卷接入设置 ->发货地址)
			'order_cancel_url' => $aO['cancelurl'], //optional string	用户取消订单跳转URL(默认为首)
		);
		$param = array_merge($param, $paramOption);
		$param['sign'] = SDOApp::createSign($param, $this->apisecret);
		$url = '';
		$url = $this->payurl . '?' . http_build_query(array_merge($param, $paramOption));

		return $url;
	}
	
	public function checkpay( $apf ) { //平台方发货回调参数检查
		if( !isset($apf['order_id']) || !isset($apf['order_price']) || !isset($apf['uid']) || !isset($apf['confirm']) || !isset($apf['time']) || !isset($apf['sign']) ) {
			return array();
		}
		$param = $p = array();
		$p['order_id'] = $param['apid'] = $apf['order_id']; //required int 订单ID
		$p['order_price'] = $param['pamt'] = $apf['order_price']; //required int 订单总金额
		$p['uid'] = $param['puid'] = $apf['uid']; //required int 用户数字ID
		$p['confirm'] = $param['flag'] = $apf['confirm']; //required int 1、确认付款，2、取消付款
		$p['time'] = $param['time'] = $apf['time']; //required int 当前的Unix时间戳，精确到秒
		$sign = $apf['sign']; //required string 签名

		if( strlen( $sign ) && $sign === SDOApp::createSign($p, $this->apisecret) ) {
			return $param;
		}

		return array();
	}

	public function payresult( $param ) { //平台方发货后的返回
		$p = array();
		$p['time'] = time();
		$p['order_id'] = $param['apid'];
		$p['confirm'] = $param['flag'];
		$sign = SDOApp::createSign( $p, $this->apisecret );
		$res = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<callback>
    <order_id>{$p['order_id']}</order_id>
    <confirm>{$p['confirm']}</confirm>
    <time>{$p['time']}</time>
    <sign>{$sign}</sign>
</callback>";
		return $res;
	}

	/**
	 * 公共调用
	 * @param array $callMethod
	 * @param array $params
	 * @return obj
	 */
	private function call( $callMethod, $params=array() ) {
		$sdoParams = array(
		    'api_key' => $this->apikey,  //常量在应用配置文件config.php里定义
		    'method' => $callMethod,
		    'v' => 1.0,
		    'call_id' => time(),
		    'session_key' => $this->pfkey,  //从cookie中获取session key，session key是在index.php里写入cookie的
		    'app_secret' => $this->apisecret, //常量在应用配置文件config.php里定义, sdk需要应用secret key来计算签名
		    'format' => 'json',
		);

		return @json_decode( SDOApp::postResult( array_merge($sdoParams, $params ) ), true );
	}
}
